import React, { Component } from 'react'
import { View, Text, StyleSheet, TextInput, Dimensions, TouchableOpacity, Image, ScrollView, Alert } from 'react-native'
import { AsyncStorage } from 'react-native';
import ImagePicker from 'react-native-image-picker';


const { width, height, scale } = Dimensions.get('window')
let gList = [];

export default class Fabiao extends Component {
    constructor() {
        super();
        this.refInput = React.createRef();
        this._onChangeText = this._onChangeText.bind(this);
        this.state = {
            showValue: "",
            tmpImgList: [],
            others: "",
            picList: []
        }
    }


    //设置输入框，获得焦点
    handleSetTnputFocus = () => {
        if (this.refInput.isFocused()) {
            //设置获得焦点
            this.refInput.focus();
        }
    }
    //选择图片 拍摄、选择本地图片
    handleSelectImage = () => {
        const options = {
            title: '选择图片',
            cancelButtonTitle: '取消',
            takePhotoButtonTitle: '拍照',
            chooseFromLibraryButtonTitle: '相册',
            storageOptions: {
                skipBackup: true,
                path: 'images',
            },
        };
        ImagePicker.showImagePicker(options, (response) => {

            const { data, ...others } = response;
            console.log(others);

            if (response.didCancel) {
                console.log('User cancelled image picker');
            }
            else if (response.error) {
                console.log('ImagePicker Error: ', response.error);
            }
            else if (response.customButton) {
                console.log('User tapped custom button: ', response.customButton);
            }
            else {
                //不能大于9张
                const { tmpImgList } = this.state;
                if (tmpImgList.length >= 9) {
                    alert('图片不能超过9张')
                    return;
                }
                tmpImgList.push(response);
                this.setState({ tmpImgList });

            }
        });
    }


    //实现本地存储和读取数据
    _onChangeText(inputData) {
        console.log("输入的内容", inputData);
        //把获取到的内容，设置给showValue
        this.setState({ showValue: inputData });
    }
    showData() {
        alert(this.state.showValue);//展示输入框的内容
    }

    getData = async () => {
        console.log('****');

        let data = await AsyncStorage.getItem('dongtai');
        data = JSON.parse(data);
        if (data == null) {
            console.log('PPPPs');
            data = [];
            return data;
        } else {
            return data;
        }
    }

    getName = async () => {
        let data = await AsyncStorage.getItem('name');
        data = JSON.parse(data);
        return data;
    }

    setText = async () => {
        //保存数据
        let time = new Date();
        let id = time.getTime();
        id = id + '';
        id = id.slice(8);

        await this.getName().then((res) => {
            let record = {
                name: res,
                pic: require('./img/111.jpg'),
                content: this.state.showValue,
                list: gList,
                id: id,
                shenP: '',
                good: 0,
                flag: true,
                isLike: false,
                isComments: false
            };
            return record
        }).then(async (res) => {
            let record = res;
            await this.getData().then(async (res) => {
                let data = res;
                data.unshift(record);
                data = JSON.stringify(data);
                return data;

            }).then(async (res) => {
                await AsyncStorage.setItem('dongtai', res)
            });
        })




    }


    //跳转方法
    async yourFunction() {
        //图片上传
        const { tmpImgList } = this.state;
        const params = new FormData();
        let list = [];
        tmpImgList.forEach(v => {
            list = [...list, v.uri];
        })
        gList = list;
        await this.setText();
        await this.props.navigation.navigate('pi');

        // this.setImg()


    }


    render() {
        const { tmpImgList } = this.state;
        return (
            <View style={styles.container}>

                <TouchableOpacity
                    style={{ height: '40%', width: '100%' }}
                    onPress={this.handleSetTnputFocus}
                    activeOpacity={1}
                >
                    <TextInput
                        ref={ref => this.refInput = ref}
                        autoCapitalize='none'
                        value={this.state.inputText}
                        placeholder='请填写动态（140字以内）'
                        multiline
                        onChangeText={this._onChangeText}
                    />
                </TouchableOpacity>
                {/* 临时相册 */}
                <View style={{ paddingTop: 5, paddingBottom: 5 }}>
                    <ScrollView horizontal>
                        {tmpImgList.map((v, key) => <Image
                            key={key}
                            source={{ uri: v.uri }}
                            style={{ marginLeft: 5, marginRight: 5, height: 100, width: 100 }}
                        />)}
                    </ScrollView>
                </View>
                {/* 工具栏 */}
                <View style={styles.bottomBox}>
                    <TouchableOpacity
                        style={{ marginLeft: 30, marginRight: 20 }}
                        onPress={this.handleSelectImage}
                    >
                        <Image id="conImg" style={styles.conImg1} source={require('./img/tupian.png')} />
                    </TouchableOpacity>
                    <TouchableOpacity
                    // style={{marginLeft:20}}
                    >
                        <Image id="conImg" style={styles.conImg} source={require('./img/biaoqing.png')} />
                    </TouchableOpacity>
                    {/* 发帖 */}
                    <TouchableOpacity style={styles.loginBtn} activeOpacity={0.7}
                        onPress={this.yourFunction.bind(this)}
                    >
                        <Text style={styles.loginTxt}>发 贴</Text>
                    </TouchableOpacity>
                </View>
            </View>
        )
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        // alignItems:'center'
    },
    container1: {
        flexDirection: 'row',
        alignItems: 'center',
        height: 45,
        alignSelf: 'stretch',
        backgroundColor: '#4a9df8',
    },
    textview: {
        flex: 1,
        alignSelf: 'center',
    },
    textstyle: {
        fontSize: 18,
        color: '#fff',
        textAlign: 'center',
    },
    bottomBox: {
        height: 50,
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#eee'
    },
    conImg: {
        width: 30,
        height: 30,
    },
    conImg1: {
        width: 40,
        height: 40
    },
    loginBtn: {
        width: 55,
        height: 35,
        backgroundColor: "skyblue",
        borderRadius: 8,
        marginTop: 2,
        marginLeft: 250
    },
    loginTxt: {
        textAlign: "center",
        lineHeight: 35,
        color: '#fff'
    },
});
